/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.uct.controller  
 */
package com.apache.uct.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.apache.api.manager.BaseManager;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.api.vo.Token;
import com.apache.database.constant.SystemTools;
import com.apache.database.constant.Validator;
import com.apache.tools.DateUtils;
import com.apache.uct.common.BaseAction;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.ActGive;
import com.apache.uct.common.entity.Dept;
import com.apache.uct.common.entity.Org;
import com.apache.uct.common.entity.User;
import com.apache.uct.manager.ActGiveManager;
import com.apache.uct.manager.ActManager;
import com.apache.uct.manager.DeptManager;
import com.apache.uct.manager.OrgManager;

/**
 * description:  部门管理Action
 * @author dwusoft 创建时间：2015-3-13  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
@Controller
@RequestMapping("uct/dept/")
public class DeptAction extends BaseAction<Dept> {

	@Autowired
	private DeptManager deptManager;
	@Autowired
	private ProxyManager uctProxyManager;
	@Autowired
	private OrgManager orgManager;
	@Autowired
	private ActManager actManager;
	@Autowired
	private ActGiveManager actGiveManager;

	/**
	 * 功能说明：通用跳转到列表查询页面
	 */
	@RequestMapping("list.action")
	public ModelAndView list(HttpServletRequest request) {
		String orgId = request.getParameter("orgId");
		ParamsVo<Org> vo = new ParamsVo<Org>();
		vo.setInfoId(orgId);
		Org org = (Org) orgManager.getInfoById(vo);
		ModelAndView view = new ModelAndView(LIST);
		view.addObject("org", org);
		return view;
	}

	@RequestMapping("dept!data.action")
	@ResponseBody
	protected Object data(HttpServletRequest request, String page, String rows) {
		ParamsVo<Dept> vo = new ParamsVo<Dept>();
		Dept dept = new Dept();
		if (Validator.isNotNull(request.getParameter("orgId"))) {
			dept.setOrgId(request.getParameter("orgId"));
		}
		String id = Validator.getDefaultStr(request.getParameter("id"), "0");
		dept.setFatherId(id);
		vo.setObj(dept);
		List<Dept> list = deptManager.getList(vo);
		net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
		for (int i = 0; i < list.size(); i++) {
			Dept deptVo = list.get(i);
			net.sf.json.JSONObject jvo = net.sf.json.JSONObject.fromObject(deptVo);
			if (null != deptVo.getCreateTime()) {
				jvo.put("createTime", DateUtils.longToStr(deptVo.getCreateTime(), DateUtils.FmtStr.CN_yyyyMMdd_HHmmss));
			}
			if (deptVo.getSubCount() != null && deptVo.getSubCount() > 0) {
				jvo.put("state", "closed");
			} else {
				jvo.put("state", "opened");
			}
			jary.add(jvo);
		}
		return jary;
	}

	/**
	 * 功能说明：跳转到新增页面
	 */
	@Token(save = true)
	@RequestMapping(value = "add.action", method = RequestMethod.GET)
	protected ModelAndView add(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(EDIT);
		ParamsVo<Dept> vo = new ParamsVo<Dept>();
		Dept dept = null;
		if (Validator.isNotNull(request.getParameter("deptId"))) {
			vo.setInfoId(request.getParameter("deptId"));
			dept = (Dept) getBaseManager().getInfoById(vo);
		} else {
			dept = new Dept();
			dept.setOrgId(request.getParameter("orgId"));
			dept.setOrgEname(request.getParameter("orgEname"));
			dept.setFatherId(Validator.getDefaultStr(request.getParameter("fatherId"), "0"));
		}
		view.addObject("item", dept);
		return view;
	}

	/**
	 * TODO 保存机构信息.  
	 */
	@Token(remove = true)
	@RequestMapping(value = "/save.action", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg save(HttpServletRequest request, HttpServletResponse response, @ModelAttribute Dept item) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		ParamsVo<Dept> vo = getParamsVo(request);
		if (Validator.isNull(item.getFatherId()))
			item.setFatherId("0");
		long times = DateUtils.toLong(new Date());
		User user = this.getSessionUser(request);
		if (Validator.isNotNull(item.getOrgId())) {
			ParamsVo ovo = new ParamsVo();
			ovo.setInfoId(item.getOrgId());
			Org org = (Org) orgManager.getInfoById(ovo);
			item.setOrgEname(org.getOrgEname());
		}
		if (Validator.isNotNull(item.getDeptId())) {//对部门信息修改
			if (!"0".equals(item.getFatherId())) {
				ParamsVo pvo = new ParamsVo();
				pvo.setInfoId(item.getFatherId());
				Dept Dept = (Dept) deptManager.getInfoById(pvo);
				item.setFullEname(Dept.getFullEname() + "/" + item.getDeptEname());
				item.setFullCname(Dept.getDeptCname() + "/" + item.getDeptCname());
			} else {
				item.setFullEname("/" + item.getDeptEname());
				item.setFullCname("/" + item.getDeptCname());
			}
			item.setUpdateTime(times);
			int updateCount = item.getUpdateCount() == null ? 0 : item.getUpdateCount();
			item.setUpdateCount(updateCount + 1);
			item.setUpdateUser(user.getUserEname());
			vo.setObj(item);
			boolean mark = getBaseManager().editInfo(vo);
			if (!mark) {
				rmsg = getResultMsg(request, "部门信息修改失败！");
			}
		} else {//添加部门信息
			if (Validator.isNull(item.getFatherId()))
				item.setFatherId("0");
			if (!"0".equals(item.getFatherId())) {
				ParamsVo pvo = new ParamsVo();
				pvo.setInfoId(item.getFatherId());
				Dept Dept = (Dept) deptManager.getInfoById(pvo);
				item.setFullEname(Dept.getFullEname() + "/" + item.getDeptEname());
				item.setFullCname(Dept.getDeptCname() + "/" + item.getDeptCname());
			} else {
				item.setFullEname("/" + item.getDeptEname());
				item.setFullCname("/" + item.getDeptCname());
			}
			item.setCreateUser(user.getUserEname());
			item.setSysEname("uct");
			item.setUpdateCount(0);
			item.setCreateTime(times);
			vo.setObj(item);
			vo.setKey("checkCodeName");
			String msg = String.valueOf(deptManager.execute(vo));
			if (Validator.isNotNull(msg)) {
				rmsg = getResultMsg(request, msg);
			} else {
				String id = getBaseManager().saveInfo(vo);
				if (Validator.isNull(id)) {
					rmsg = getResultMsg(request, "部门信息修改失败！");
				}
			}
		}
		return rmsg;
	}

	//删除部门信息
	@RequestMapping("del.action")
	@ResponseBody
	public ResultMsg delete(HttpServletRequest request, String id) {
		ResultMsg rmsg = new ResultMsg("T", "删除成功！");
		ParamsVo<Dept> vo = getParamsVo(request);
		if (isNotNull(id)) {
			vo.setInfoId(id);
			vo.setKey("deleteOrg");
			vo.setParams("infoType", "dept");
			String msg = String.valueOf(uctProxyManager.doInvoke(vo));
			if (Validator.isNotNull(msg)) {
				rmsg.setFlag("F");
				rmsg.setMsg(msg);
			}
		} else {
			rmsg.setFlag("H");
			rmsg.setMsg("请选择要删除的部门！");
		}
		return rmsg;
	}

	//检查是否设置授权权限
	@RequestMapping("dept-act!checkAct.action")
	@ResponseBody
	public ResultMsg checkAct(HttpServletRequest request) {
		ResultMsg rmsg = new ResultMsg("T", "成功！");
		if (!"1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {//是否开启授权
			rmsg = new ResultMsg("F", "对不起,您没有此功能的操作权限!");
		}
		return rmsg;
	}

	//跳转到机构授权页面
	@RequestMapping("dept-act.action")
	public ModelAndView list(HttpServletRequest request, String deptId) {
		ModelAndView view = new ModelAndView(getPrefix() + "act");
		view.addObject("deptId", deptId);
		return view;
	}

	/**
	 * 获取权限分配列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("dept-act!data.action")
	@ResponseBody
	public Object dataActs(HttpServletRequest request, String deptId, String id) throws Exception {
		id = Validator.getDefaultStr(id, "0");
		Act actVo = new Act();
		actVo.setFatherId(id);
		ParamsVo<Act> vo = new ParamsVo<Act>();
		vo.setObj(actVo);
		User user = this.getSessionUser(request);
		if (!Validator.isEmpty(user)) {
			vo.setParams("userOrgId", user.getOrgId());
			vo.setParams("sysUser", getSysFlag(request));//是否为系统用户
		}
		vo.setKey("findActForOrg");
		List<Act> actList = (List<Act>) uctProxyManager.doInvoke(vo);
		ParamsVo<ActGive> agVo = new ParamsVo<ActGive>();
		agVo.setParams("roleId", deptId);
		agVo.setParams("giveType", "dept");
		agVo.setKey("GiveListByOrgId");
		List<ActGive> giveList = (List<ActGive>) actGiveManager.execute(agVo);

		JSONArray jary = new JSONArray();
		for (int i = 0; i < actList.size(); i++) {
			Act act = actList.get(i);
			JSONObject jvo = JSONObject.fromObject(act);
			if (act.getSubCount() != null && act.getSubCount() > 0) {
				jvo.put("state", "closed");
			} else {
				jvo.put("state", "opened");
			}
			String hasGive = hasGive(giveList, act.getActId()) ? "T" : "F";
			jvo.put("hasGive", hasGive);
			jary.add(jvo);
		}
		return jary;
	}

	/**
	 * description:  部门下用户列表
	 */
	@RequestMapping("dept-users.action")
	protected ModelAndView deptUsers(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(getPrefix() + "users");
		ParamsVo<Dept> vo = new ParamsVo<Dept>();
		Dept dept = null;
		if (Validator.isNotNull(request.getParameter("deptId"))) {
			vo.setInfoId(request.getParameter("deptId"));
			dept = (Dept) getBaseManager().getInfoById(vo);
			view.addObject("item", dept);
		}
		return view;
	}

	/**
	 * 添加用户界面  初始化该机构下的部门
	 */
	@RequestMapping("dept!initDept.action")
	@ResponseBody
	public Object initDept(HttpServletRequest request, String orgId) throws Exception {
		ParamsVo<Dept> vo = new ParamsVo<Dept>();
		Dept dept = new Dept();
		dept.setOrgId(orgId);
		vo.setObj(dept);
		List<Dept> list = deptManager.getList(vo);
		net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
		if (Validator.isEmpty(list)) {
			return jary;
		}

		for (int i = 0; i < list.size(); i++) {
			Dept dvo = list.get(i);
			net.sf.json.JSONObject jvo = new net.sf.json.JSONObject();
			jvo.put("deptId", dvo.getDeptId());
			jvo.put("deptCname", dvo.getDeptCname());
			jary.add(jvo);
		}
		return jary;
	}

	protected BaseManager<Dept> getBaseManager() {
		return deptManager;
	}

	protected String getPrefix() {
		return "uct/dept-";
	}

	/**
	 * 判断是否包含该权限值
	 * @param giveList 分配的权限值
	 * @param actId 权限值id
	 * @return boolean
	 */
	private boolean hasGive(List<ActGive> giveList, String actId) {
		if (Validator.isEmpty(giveList))
			return false;
		for (int j = 0; j < giveList.size(); j++) {
			ActGive give = giveList.get(j);
			if (actId.equals(give.getActId())) {
				return true;
			}
		}
		return false;
	}

}
